/**
 * 
 */
package uk.ac.lkl.lpp.ui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.URL;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.MissingResourceException;
import java.util.logging.Logger;

import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.SwingConstants;
import javax.swing.JComboBox;


import org.jdesktop.jdic.desktop.Desktop;

import uk.ac.lkl.common.util.Resources;

/**
 * @author yish
 *
 */
public final class Messages extends PropertyResourceBundle {

	private static final Logger logger = Logger.getLogger("uk.ac.lkl.lpp");
	protected static String locator = Messages.class.getName();
	protected static ResourceBundle bundle = PropertyResourceBundle.getBundle(locator);;

    public static final String TIP_KEY         = ".tip";
    public static final String LABEL_KEY       = ".label";
    public static final String DESCRIPTION_KEY = ".description";
    public static final String LINK_KEY        = ".link";
    public static final String ICON_KEY        = ".icon";
    
    private static String LINK_ICON_LOCATION = "gfx/link.gif";
    public static final ImageIcon LINK_ICON    = Resources.getIcon(LINK_ICON_LOCATION); 
    
    private static boolean generate = false;
    
    /**
     * if generate == true write out labels to out.
     */
    private static PrintStream out = null;
    
	
	public Messages(InputStream stream) throws IOException {
		super(stream);
	}

	public static ResourceBundle getBundle() {
		return bundle;
	}
	
	public static void setLocator(String l){
		locator = l;
		bundle = PropertyResourceBundle.getBundle(locator);
	}
	
	public static void loadFromStream(InputStream in) throws IOException {
		bundle = new PropertyResourceBundle(in);
	}
	
	public static void loadFromFile(String fileName)throws IOException {
		loadFromStream(new FileInputStream(fileName));
	}
	
	public static final void loadFromFile(File file) throws IOException {
		loadFromStream(new FileInputStream(file));
	}
	
	public static final String cleanKey(String key){
		if (key == null) return null;
		return key.replace(" ", "_");
	}
	
    /**
     * Write out labels to out.
     */
	public static final void setOutputStream(OutputStream out){
		generate = true;
		if (out.getClass().equals(PrintStream.class)) {
			Messages.out = (PrintStream) out;
		} else {
			Messages.out = new PrintStream(out); 
		}
		

	}
	
	private static final void generate(String key) {
		if (!generate || out == null || key == null) return;
		out.println(cleanKey(key)+" =");
	}

	private static final void generate(String key, String value) {
		if (!generate || out == null || key == null) return;
		out.print(cleanKey(key));
		out.print(" =");
		if (value != null && value.length() > 0) out.print(value);
		out.println();
	}

	private static final String getValue(String key) {
		String k = cleanKey(key);
		try {
			String value = bundle.getString(k);
			logger.fine(k+"="+ value);
			generate(k, value);
			return value;
		} catch (MissingResourceException e) {
			return null;
		}		
	}
	public static final String getTip(String key) {
		return getValue (key+TIP_KEY);
	}
	
	public static final String getLabel(String key) {
		return getValue (key+LABEL_KEY);
	}

	public static final String getDescription(String key) {
		return getValue (key+DESCRIPTION_KEY);
	}

	public static final String getLink(String key) {
		return getValue (key+LINK_KEY);
	}
	
	public static final ImageIcon getIcon(String key) {
		String k = cleanKey(key);
		try {
			logger.fine(k); 
			generate(k+ICON_KEY);
			String iconLocator = bundle.getString(k+ICON_KEY);
			if (iconLocator == null) return null;
			return Resources.getIcon(iconLocator);
		} catch (MissingResourceException e) {
			return null;
		}
	}

	/**
	 * Create a JLabel for this key. Extract the label and tip text from the resource bundle.
	 * @param key query the resource bundle for label and tooltip per this key, 
	 * 		if no label found use key.
	 * @return
	 */
	public static final JLabel getJLabel(String key) {
		String k = cleanKey(key);
		logger.fine(k); 
		String label = getLabel(k);
		ImageIcon icon = getIcon(k);
		JLabel jl = null;
		
		if (label == null && icon == null) label = k;
        jl = new JLabel(label,icon,SwingConstants.LEADING);

        // add tip
        String tip = getTip(k);
        if (tip != null && tip.length() > 0) jl.setToolTipText(tip);

        return jl;
        
        //Desktop.browse(new URL(linkable.getLink()));
	}
	
	/**
	 * create a JCombo for this key. Parse the key value as a comma-seperated list 
	 */
	public static final JComboBox getJCombo(String key){
		String k = cleanKey(key);
		logger.fine(k); 
		String value = getLabel(k);
		
		if (value == null || value.length() == 0) {
			return new JComboBox(new String[]{key});
		}
		String[] vals = value.split(",");
		
		return new JComboBox(vals);
	}

	/**
	 * Create a JButton for this key. Extract the label and tip text from the resource bundle.
	 * @param key query the resource bundle for label and tooltip per this key, 
	 * 		if no label found use key.
	 * @return
	 */
	public static final JButton getJButton(String key) {
		String k = cleanKey(key);
		logger.fine(k); 
		String label = getLabel(k);
		ImageIcon icon = getIcon(k);
		if (label == null && icon == null) label = k;
        String tip = getTip(k);
        String link = getLink(k);

		return makeJButton(label,icon,tip,link);
	}
	
	/**
	 * create a button with optional tip, icon and link
	 * if any of these are null - ignore them.
	 */
	public static final JButton makeJButton(String label, ImageIcon icon, String tip, String link) {
		JButton jb = new JButton(label,icon);
        // add tip
        if (tip != null && tip.length() > 0) jb.setToolTipText(tip);
        // add link
        if (link != null && link.length() > 4) {
        	jb.addActionListener(new LinkActionListener(link));
        	jb.setRolloverIcon(LINK_ICON);
        }
        return jb;
	}
	
	/**
	 * Create a JButton for this key. Extract the label and tip text from the resource bundle.
	 * @param key query the resource bundle for label and tooltip per this key, 
	 * 		if no label found use key.
	 * @return	private final static class LinkActionListener implements ActionListener {
		private final String link;
		
		public LinkActionListener(String link) {
			this.link = link;
		}

        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.browse(new URL(link)); //Throws an error
            }
            catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    }

	 */
	public static final JButton getJButton(String key, boolean flat) {
		logger.fine(key); 
		JButton jb = getJButton(key);
		if (flat) jb.setBorderPainted(false);
		return jb;
	}
	

	private final static class LinkActionListener implements ActionListener {
		private final String link;
		
		public LinkActionListener(String link) {
			this.link = link;
		}

        public void actionPerformed(ActionEvent e) {
            try {
                Desktop.browse(new URL(link)); //Throws an error
            }
            catch (Exception exc) {
                exc.printStackTrace();
            }
        }
    }

}

